<?php

namespace app\admin\controller\dingdan;

use app\common\controller\Backend;
use app\admin\model\Cloudphone;
use app\admin\service\PhoneService;
use app\admin\model\Orders as OrdersModel;
use think\Queue;
/**
 * 云手机列表
 *
 * @icon  fa fa-tv
 */
class Phone extends Backend
{
    public function _initialize()
    {
        $model = new Cloudphone();
        $statusList = $model->statusList();
        $this->view->assign('statusList',$statusList);
        parent::_initialize();
    }
    /**
     * View
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null);
            $is_delete = input('is_delete',-1);
            $sort = 'status';
            $list = (new Cloudphone())
                ->with(['package'])
                ->where($where)
                ->where('is_delete',$is_delete)
                ->order($sort, 'desc')
                ->paginate($limit);

            $data = $list->items();
            $orderModel = new \app\admin\model\Orders();
            foreach ($data as &$one){
                $hasOrder = db('cloudphone_order')->where('phone_id',$one['id'])->where('status',$orderModel::STATUS_HASPAY)->find();
                if($hasOrder){
                    $one['is_use'] = 1;
                }else{
                    $one['is_use'] = -1;
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items(),"extend"=>[]);

            return json($result);
        }

        return $this->view->fetch();

    }

    /**
     * Add
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if(empty($params['name'])){
                $this->error("名字不为空！");
            }

            if(empty($params['instance_code'])){
                $this->error("实例编号不为空！");
            }
            if(empty($params['package_id'])){
                $this->error("请选择套餐分类！");
            }

            $find = db('cloudphone')->where('instance_code',$params['instance_code'])->find();
            if($find){
                $this->error("该实例编号已存在！");
            }
            $params['create_time'] = date("Y-m-d H:i:s");
            $params['update_time'] = date("Y-m-d H:i:s");
            unset($params['id']);
            db('cloudphone')->insertGetId($params);

            Queue::push('\app\job\InstallApp', ['instance_code'=>$params['instance_code'],'order_no'=>rand(111,9999)]);
            $this->success("添加成功");
        }

        $packageData = db('package')->where('id','>',0)->select();
        $this->view->assign('id',0);
        $this->view->assign('packageData',$packageData);
        $this->view->assign('data',[]);
        $this->view->assign('status',1);
        $this->view->assign('type',1);
        return $this->view->fetch('add');

    }

    /**
     * Edit
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if(empty($params['name'])){
                $this->error("名字不为空！");
            }
            if(empty($params['instance_code'])){
                $this->error("实例编号不为空！");
            }

            if(empty($params['package_id'])){
                $this->error("请选择套餐分类！");
            }
            $find = db('cloudphone')->where('instance_code',$params['instance_code'])->find();
            if($find && $find['id'] != $params['id']){
                $this->error("该实例编号已存在！");
            }
            unset($params['id']);
            db('cloudphone')->where('id',$ids)->update($params);
            $this->success("修改成功");
        }


        $data = db('cloudphone')->where('id',$ids)->find();
        $packageData = db('package')->where('id','>',0)->select();
        $this->view->assign('packageData',$packageData);
        $this->view->assign('id',$ids);
        $this->view->assign('data',$data);
        $this->view->assign('status',$data['status']);
        return $this->view->fetch('add');
    }

    /**
     * Del
     */
    public function del($ids = null)
    {
        if(empty($ids))
            $this->error(__('Error Parame'));

        //在排課系統没有的话就删除
        $ids = explode(',',$ids);
        $error = [];
        foreach ($ids as $id){
            $hasOne = db('cloudphone_order')->where('phone_id',$id)->find();
            if(empty($hasOne)){
                db('cloudphone')->where('id',$id)->delete();
            }else{
                db('cloudphone')->where('id',$id)->update(['is_delete'=>1]);
            }

        }
        $this->success("删除成功");
    }

    /**
     * 重启手机
     */
    public function reboot($ids = null){
        if(empty($ids))
            $this->error(__('Error Parame'));

        $phoneData = db('cloudphone')->where('id',$ids)->find();
        $phoneServiceHandle = new PhoneService();
        $result = $phoneServiceHandle->reboot($phoneData['instance_code']);
        if($result){
            $this->success("重启成功");
        }else{
            $this->error($phoneServiceHandle->errorMsg);
        }
    }

    /**
     * 授权登录
     */
    public function authlogin($ids = null){
        if(empty($ids))
            $this->error(__('Error Parame'));

        $phoneData = db('cloudphone')->where('id',$ids)->find();
        if($phoneData['init_status'] == 2){
            return dataReturn(-1,'机器正在就绪中，稍等1分钟');
        }
        $hasOrder = db('cloudphone_order')->where('phone_id',$phoneData['id'])->where('status',OrdersModel::STATUS_HASPAY)->find();
        if($hasOrder){
            $this->error("暂不支持授权登录，有玩家已租用中");
        }
        $phoneServiceHandle = new PhoneService();
        $uuid = uniqid();
        $serverToken = $phoneServiceHandle->serverToken($uuid,$phoneData['instance_code'],3600);
        if($serverToken){
            $loginurl = request()->domain()."/index/phone/index?uuid={$uuid}&token={$serverToken}";
            $this->success("重启成功",'',['loginurl'=>$loginurl]);
        }else{
            $this->error($phoneServiceHandle->errorMsg);
        }
    }
}
